﻿using System.Text.Json.Serialization;
using Core.Caching;
using Core.Domain.Entities;
using Core.Domain.ValueObjects;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Identity.UserProfiles.Caching;
using Core.Identity.UserProfiles.Dtos;
using Core.Interfaces.Users;
using Core.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.UserProfiles.Features.Commands.Edit;

/// <summary>
/// 编辑用户偏好
/// </summary>
public class EditUserProfileCommand : ICacheInvalidatorRequest<Result<bool>>
{
    /// <summary>
    /// 用户偏好
    /// </summary>
    public required IEnumerable<UserPreferenceDto> Preferences { get; set; }

    [JsonIgnore]
    public IEnumerable<string>? Tags => UserProfilesCacheKey.Tags;
}

public class EditUserProfileCommandHandler(IIdentityDbContext dbContext, ICurrentUserService currentUser)
    : IRequestHandler<EditUserProfileCommand, Result<bool>>
{

    public async Task<Result<bool>> Handle(EditUserProfileCommand request, CancellationToken cancellationToken)
    {
        var userId = currentUser.GetUserId();
        // 查询用户档案
        var userProfile = await dbContext.UserProfiles
            .Include(x => x.Preferences)
            .FirstOrDefaultAsync(x => x.UserId == userId, cancellationToken);

        // 不存在就创建
        if (userProfile == null)
        {
            userProfile = new UserProfile(userId);
            dbContext.UserProfiles.Add(userProfile);
        }

        // 批量设置偏好项（已存在更新，未存在新增）
        var preferences = request.Preferences
            .Select(p => UserPreference.Create(p.Key, p.Value, p.Description));

        userProfile.SetPreferences(preferences);

        var result = await dbContext.SaveChangesAsync() > 0;

        return await Result<bool>.SucceedAsync(result, result, ["编辑失败"]);
    }
}
